﻿namespace EzDesk.DesktopClient.MessageModule
{
    using Event;
    using System.Collections.Generic;
    using EventAggregation;
    using Generic;
    using Model;
    using Generic.Collections;
    using System.Linq;
    using MVVMEnhance;

    public class FeedViewModel : ViewModelWithSingleContainer<IFeedView>
    {
        public RangeCollection<FeedItemViewModel> UpdateFeeds
        {
            get;
            set;
        }
        public FeedViewModel()
            : base()
        {
            InitMember();
            InitEvent();
        }

        private void InitMember()
        {
            this.UpdateFeeds = new RangeCollection<FeedItemViewModel>();
            ResetFeedCollectionRange();
        }

        
        private void InitEvent()
        {
            this.InitGlobalEvent();
            this.InitLocalEvent();
        }

        private void InitGlobalEvent()
        {
            FeedPushEvent.Instance.Subscribe(this.OnFeedUpdate, ThreadOption.UIThread);
        }
        private void InitLocalEvent()
        {

        }

        private void ResetFeedCollectionRange()
        {
            this.UpdateFeeds.ResetMaxCount(ClientConfigurationManagement.Instance.FeedDisplayCount);
        }

        private void OnFeedUpdate(FeedPushArgs args)
        {
            ResetFeedCollectionRange();
            UpdateData(args.UpdateCollection);
        }

        private void UpdateData(IEnumerable<Feed> updateCollection)
        {
            updateCollection.Reverse().Foreach(u => this.UpdateFeeds.InsertItemAtFirst(this.GenerateViewModel(u)));
        }

        private FeedItemViewModel GenerateViewModel(Feed model)
        {
            return new FeedItemViewModel(model);
        }
    }
}